#include <thread>
#include <list>
#include <mutex>
#include "SLT_log.h"
#include "SLT_memory.h"
struct SLT_memLeakObjInfoInner
{
	std::string  m_name;
	SLT_memLeakObjInfo* m_pobj;
};
struct SLT_memLeakCheckGInfo
{
	int m_showTime = 5;
	bool m_show_0 = false;
	std::mutex   m_newListLock;
	std::list< SLT_memLeakObjInfoInner*>  m_curlist;
};

static SLT_memLeakCheckGInfo  *g_pmemLeakCheck_220513 = nullptr;
static void  SLT_memLeak_thread()
{
	while (1) {
		for (auto& item : g_pmemLeakCheck_220513->m_curlist) {
			if (g_pmemLeakCheck_220513->m_show_0) {
				//SLT_WriteLog(0, "[mem]%s,count:%u\n", item->m_name.c_str(), (uint32_t)item->m_pobj->m_count);
				SLT_LOG(1, SLT_WARM,"[mem]%s,count:%u", item->m_name.c_str(), (uint32_t)item->m_pobj->m_count);
			}
			else {
				if (item->m_pobj->m_count != 0) {
					//SLT_WriteLog(0, "[mem]%s,count:%u\n", item->m_name.c_str(), (uint32_t)item->m_pobj->m_count);
					SLT_LOG(1, SLT_WARM,"[mem]%s,count:%u", item->m_name.c_str(), (uint32_t)item->m_pobj->m_count);
				}
			}
		}
		std::this_thread::sleep_for(std::chrono::seconds(g_pmemLeakCheck_220513->m_showTime));
	}
}
SLT_API int SLT_memLeakInit(int _showtime_s, bool _show_0)
{
	if (g_pmemLeakCheck_220513) {
		return -1;
	}
	g_pmemLeakCheck_220513 = new SLT_memLeakCheckGInfo;
	g_pmemLeakCheck_220513->m_showTime = _showtime_s;
	g_pmemLeakCheck_220513->m_show_0 = _show_0;
	std::thread(SLT_memLeak_thread).detach();
	return 0;
}
SLT_API void SLT_memLeak_addobj(const char* pname, SLT_memLeakObjInfo* _pinfo)
{
	if (! g_pmemLeakCheck_220513) {
		return ;
	}

	SLT_memLeakObjInfoInner* pobj = new SLT_memLeakObjInfoInner;
	pobj->m_name = pname;
	pobj->m_pobj = _pinfo;
	g_pmemLeakCheck_220513->m_newListLock.lock();
	g_pmemLeakCheck_220513->m_curlist.push_back(pobj);
	g_pmemLeakCheck_220513->m_newListLock.unlock();
}
